<template>
    <div class="branding-layout">

        <!-- 初始化加载中 -->
        <UxIniting v-if="!inited" />

        <!-- 编辑 -->
        <BrandingHangtagManage ref="manage" v-else-if="detail" :detail="detail" @update="getData()" @close="detailClose()" />

        <!-- 空数据 -->
        <div class="branding-nodata" v-else-if="inited && table.length == 0">

            <div class="branding-nodata-banner">
                <img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-icon.png">
                <h2>Incorporate a Compelling Hang Tag in <br> Your Clothing Brand</h2>
                <button type="primary" @click="detailOpen()">Create hang tag</button>
            </div>

            <div class="branding-nodata-bring">
                <h2>Understand the benefits of a unique hang tag</h2>
                <ul>
                    <li>
                        <figure><img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-bring-1.png"></figure>
                        <p>Hang tags can create a powerful effect that differentiates your brand from others.</p>
                    </li>
                    <li>
                        <figure><img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-bring-2.png"></figure>
                        <p>A well-designed hang tag voices your creativity and the unmatched features of your products.</p>
                    </li>
                    <li>
                        <figure><img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-bring-3.png"></figure>
                        <p>Use a high-quality custom hang tag to connect with your customers and build a sustainable clothing line.</p>
                    </li>
                </ul>

            </div>

            <div class="branding-nodata-freedom">
                <h2>Start creating your own hang tag with our built-in design tool</h2>
                <h3>Another opportunity to tap into your creative potential</h3>
                <figure><img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-banner.jpg"></figure>
                <p>You are free to decide how to arrange all the elements and impress your customers with delicate details.</p>

                <button type="primary" @click="detailOpen()">Create hang tag</button>
            </div>

        </div>

        <!-- 列表 -->
        <div class="branding-list" v-else>

            <UserFixedHead title="Custom hang tag" />

            <div class="branding-list-title">
                <strong>Custom hang tag</strong>
                <span>
                    <button type="primary" disabled v-if="table.length >= 10">Template limit reached</button>
                    <button type="primary" v-else @click="detailOpen()">Create hang tag</button>
                </span>
            </div>

            <div class="branding-list-warp">

                <table>
                    <thead>
                        <th>Preview</th>
                        <th>Information</th>
                        <th>Designs</th>
                        <th>Price</th>
                        <th>Linked product(s)</th>
                        <th>Linked store(s)</th>
                        <th>Actions</th>
                    </thead>

                    <tbody>
                        <tr v-for="item in table" :key="item.id">
                            <td class="table-input">
                                <BrandingThumbPreview :pieces="item.design_list" :models="item.model_img" type="tag" />
                                <UxTemplateInputInline v-model="item.template_name" @focus="item.cache_name = item.template_name;" @change="updateName($event, item)" @blur="updateName($event, item)"></UxTemplateInputInline>
                            </td>
                            <td class="table-description">
                                <p v-if="item.hang_tag_id">
                                    <span v-text="item.name"></span>
                                    <span v-text="item.description"></span>
                                </p>
                                <p v-else>Undetermined</p>
                            </td>
                            <td class="table-print">
                                <p v-if="item.design_list.filter(i=>i.output_img).length == 0">Undetermined</p>
                                <UxPopper v-else>
                                    <strong>Artwork</strong>
                                    <BrandingPiecesPreview slot="pop" :pieces="item.design_list" effect="popper" />
                                </UxPopper>
                            </td>
                            <td class="table-price">
                                <p v-if="item.state == 1">--</p>
                                <CommonLevelDiscount v-else :price="item.total_price" :level="userInfo.level" type="unit|discount|icon" />
                            </td>
                            <td class="table-sync">
                                <span v-if="item.state == 1">--</span>
                                <p v-else-if="item.sync_count == 0" @click="disconnect_product = item">0</p>
                                <p v-else v-text="item.sync_count" @click="disconnect_product = item"></p>
                            </td>
                            <td class="table-store">
                                <span v-if="item.state == 1">--</span>
                                <div class="table-store-nodata" v-else-if="item.shop_list.length == 0" @click="disconnect_store = item">
                                    <svg-icon name="user-shop" />
                                    <span>Unlinked</span>
                                </div>
                                <div v-else class="table-store-list" @click="disconnect_store = item">
                                    <StoreIconName v-for="shop in item.shop_list" :key="shop.id" :item="shop" />
                                </div>
                            </td>
                            <td class="table-actions">
                                <!-- 默认 1：草稿  2：正常 -->
                                <button @click="detailOpen(item)">Edit</button>
                                <button v-if="item.state == 1" @click="removeBrand(item)">Delete</button>
                                <button v-else @click="connect = item">Manage</button>
                            </td>
                        </tr>
                    </tbody>
                </table>

            </div>

            <!-- 有内容 -->
            <UxLoading2 v-show="loading" />
        </div>

        <!-- 绑定对话框 -->
        <BrandingConnectManage type="hangtag" v-model="connect" @update="getData()" />

        <!-- 解绑模板或商品对话框 -->
        <BrandingDisconnectProduct type="hangtag" v-model="disconnect_product" @update="getData()" />

        <!-- 解绑店铺 -->
        <BrandingDisconnectStore type="hangtag" v-model="disconnect_store" @update="getData()" />

        <!-- 编辑对话框 -->
        <UxDialog :visible="!!dialog_edit" class="dialog-edit" @close="dialog_edit = null">
            <figure><img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-edit.png" alt=""></figure>
            <p>
                <strong>Are you sure you want to modify this hang tag?</strong>
                <span>Once you confirm the modification, all the product templates using the previous hang tag design will be updated.</span>
            </p>
            <fieldset>
                <button type="primary" @click="dialog_edit()">Confirm</button>
            </fieldset>
        </UxDialog>

        <!-- 删除 -->
        <UxDialog :visible="!!dialog_remove" class="dialog-remove" @close="dialog_remove = null">
            <figure><img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-remove.png" alt=""></figure>
            <p>
                <strong>Are you sure you want to delete this hang tag?</strong>
                <span>Once deleted, it cannot be restored.</span>
            </p>
            <fieldset>
                <button @click="dialog_remove()">Confirm</button>
                <button type="primary" @click="dialog_remove = null">Cancel</button>
            </fieldset>
        </UxDialog>

        <!-- 离开对话框 -->
        <UxDialog class="dialog-leave" :visible="!!dialog_leave" @close="dialog_leave && dialog_leave(false)">
            <!-- title="Do you want to leave?" -->
            <figure><img src="https://img.podpartner.com/static/images-20230202/brand/hangtag-icon.png" alt=""></figure>
            <p>
                <strong>Are you sure you want to leave the current page?</strong>
                <span>Once you leave, the changes you made may not be saved.</span>
            </p>
            <fieldset>
                <button @click="dialog_leave && dialog_leave(true)">Leave</button>
                <button @click="dialog_leave && dialog_leave(false)" type="primary">Stay</button>
            </fieldset>
        </UxDialog>

    </div>
</template>
<script>
import DesignResource from "@/utils/DesignResource.js";
import { mapGetters, mapState } from "vuex";

export default {
    name: "UserHangtag",
    layout: "layout-user",
    data () {
        return {
            inited: false,
            loading: true,
            detail: null,
            connect: null,

            disconnect_product: null,
            disconnect_store: null,

            dialog_edit: null,
            dialog_remove: null,
            dialog_leave: null,

            form: { num: 1, size: 10, total: 0 },
            table: [],
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
    },
    methods: {

        // 获取数据
        async getData () {



            // // 款式S001
            // const test = [{ "id": 1, "surface_name": "Front Side", "name": "Front Side", "mask_image": "hangtag/front1698720745879.png", "outer_width": 2048, "outer_height": 2048, "mask_color": "", "mask_opacity": 0, "mapping_top": true, "mapping": "[{\"canvas_name\":\"Front Side\",\"variant_deform\":0,\"variant_factor\":0,\"height\":1452,\"width\":820,\"rotate\":0,\"clip\":\"\",\"x\":614,\"y\":397}]" }, { "id": 1, "surface_name": "Back Side", "name": "Back Side", "mask_image": "hangtag/back1698908275625.png", "outer_width": 2048, "outer_height": 2048, "mask_color": "", "mask_opacity": 0, "mapping_top": true, "mapping": "[{\"canvas_name\":\"Back Side\",\"variant_deform\":0,\"variant_factor\":0,\"height\":1452,\"width\":820,\"rotate\":0,\"clip\":\"\",\"x\":614,\"y\":397}]" }]


            // // 款式S002
            // [{"id":1,"surface_name":"Front Side","name":"Front Side","mask_image":"hangtag/front1698908306798.png","outer_width":2048,"outer_height":2048,"mask_color":"","mask_opacity":0,"mapping_top":true,"mapping":"[{\"canvas_name\":\"Front Side\",\"variant_deform\":0,\"variant_factor\":0,\"height\":1452,\"width\":820,\"rotate\":0,\"clip\":\"\",\"x\":614,\"y\":397}]"},{"id":1,"surface_name":"Back Side","name":"Back Side","mask_image":"hangtag/back1698908315633.png","outer_width":2048,"outer_height":2048,"mask_color":"","mask_opacity":0,"mapping_top":true,"mapping":"[{\"canvas_name\":\"Back Side\",\"variant_deform\":0,\"variant_factor\":0,\"height\":1452,\"width\":820,\"rotate\":0,\"clip\":\"\",\"x\":614,\"y\":397}]"}]



            this.loading = true;
            let response = await this.$http("BrandHangtag.search", {});
            if (response.code === 0) {
                const table = response.data || [];

                table.map(item => {

                    item.shop_list = item.shop_list || []
                    item.cache_name = item.template_name;
                    item.loading = false;
                    try {
                        item.design_list = JSON.parse(item.design_list || '[]');
                        item.design_list.map(piece => piece.layers = JSON.parse(piece.layers || '[]'))
                        item.model_img = JSON.parse(item.model_img || '[]');
                        // item.model_img = test;
                    } catch (error) {
                        console.log(error)
                    }
                })

                this.table = table;
                this.inited = true;
                this.loading = false;
            } else {
                this.inited = true;
                this.loading = false;
                this.$uxMessage.error(response.msg || "error");
                // 提示
            }
        },

        async updateName (event, item) {

            let value = item.template_name.trim()

            if (item.loading == true) {
                // 正在加载中的不管
            } else if (item.cache_name == value) {
                // 值相同的不管
            } else if (!/[\w\W]+/.test(value)) {
                item.template_name = item.cache_name;
                this.$uxMessage.error("At least one character");
            } else {
                item.loading = true;
                let response = await this.$http("BrandHangtag.rename/" + item.id, { template_name: value });

                if (response.code === 0) {
                    item.loading = false;
                    item.cache_name = value;
                    this.$uxMessage.success("Successfully Renamed!");
                } else {
                    item.loading = false;
                    this.$uxMessage.error("Rename, failed, please try again!");
                }
            }

        },

        // 删除
        removeBrand (item) {

            this.dialog_remove = () => {

                this.dialog_remove = null;
                this.loading = true;
                this.$http("BrandHangtag.remove/" + item.id).then(response => {
                    if (response.code === 0) {
                        this.$uxMessage.success('Successfully deleted')
                        this.getData();
                    } else {
                        this.loading = false;
                        this.$uxMessage.error('Delete failed, please try again!')
                    }
                })
            }

        },

        // 打开详情
        detailOpen (detail) {
            if (!detail) {
                this.detail = {}
                document && (document.documentElement.scrollTop = 0);
            } else if (detail.state == 2) {
                // 正常的
                if (detail.sync_count == 0 && detail.shop_list.length == 0) {
                    // 未绑定的状态
                    this.detail = detail;
                    document && (document.documentElement.scrollTop = 0);
                } else {
                    // 已经有绑定
                    this.dialog_edit = () => {
                        this.dialog_edit = null;
                        this.detail = detail;
                        document && (document.documentElement.scrollTop = 0);
                    }
                }
            } else if (detail.loading) {
                // 正在加载中的不管
            } else {
                // 草稿状态
                this.detail = detail;
                document && (document.documentElement.scrollTop = 0);
            }
        },

        // 关闭详情
        detailClose () {
            if (this.canLeave()) {
                this.detail = null;
                this.$nextTick(e => document.documentElement.scrollTop = 0)
            } else {
                this.dialog_leave = (leave) => {
                    if (leave) {
                        this.detail = null;
                        this.dialog_leave = null;
                        this.$nextTick(e => document.documentElement.scrollTop = 0)
                    } else {
                        this.dialog_leave = null;
                    }

                }
            }
        },


        // 是否可离开
        canLeave () {
            if (this.$refs.manage && this.$refs.manage.change) {
                return false;
            } else {
                return true;
            }
        },

        // 分页数据改变
        changePage: function (type, value) {
            this.form.num = value;
            this.getData();
        },
    },
    created () {
        if (process.client) {
            this.getData()

            // 加载字体
            DesignResource.loadAllFont();
            this.$on('global:beforeLogout', () => new Promise((res, rej) => {
                if (this.canLeave()) {
                    res(true)
                } else {
                    this.dialog_leave = (leave) => {
                        if (leave) {
                            this.dialog_leave = null;
                            window.onbeforeunload = null;
                            setTimeout(() => res(true), 10)
                        } else {
                            this.dialog_leave = null;
                            setTimeout(() => res(false), 10)
                        }
                    }
                }
            }))
            window.onbeforeunload = (event) => {
                let notify = "Changes That you made may not be saved.";
                if (this.canLeave()) {
                } else {
                    (event || window.event).returnValue = notify;
                    return notify;
                }
            };
        }
    },

    // 路由离开
    beforeRouteLeave (to, from, next) {
        if (this.canLeave()) {
            window.onbeforeunload = null;
            next();
        } else {
            next(false);
            this.dialog_leave = (leave) => {
                if (leave) {
                    this.dialog_leave = null;
                    window.onbeforeunload = null;
                    next()
                } else {
                    this.dialog_leave = null;
                }
            }

        }
    },

};
</script>
<style lang="scss" scoped>
.branding-layout {
    position: relative;
    display: flex;
    flex-direction: column;
    & > .initing {
        flex: 1;
        width: 100%;
    }
}

.branding-init {
    flex: 1;
    position: relative;
    background: #fff;
    border-radius: 8px;
    display: flex;
    z-index: initial;

    p {
        width: 100%;
        position: relative;
    }
}

.branding-nodata {
    flex: 1;
    position: relative;
    background: #fff;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    padding: 60px 150px;

    .branding-nodata-banner {
        padding: 52px 50px 52px;
        background: #dcedf2;
        border-radius: 18px;
        display: flex;
        flex-direction: column;
        align-items: center;

        img {
            width: 76px;
            height: 76px;
        }

        h2 {
            margin-top: 20px;
            font-size: 28px;
            font-weight: bold;
            color: #000000;
            line-height: 34px;
            text-align: center;
        }
        button {
            margin-top: 20px;
            border-radius: 6px;
            width: 166px;
            height: 40px;
            font-size: 14px;
        }
    }

    .branding-nodata-bring {
        margin-top: 120px;
        h2 {
            font-size: 24px;
            font-weight: bold;
            color: #000000;
            line-height: 26px;
            text-align: center;
        }
        ul {
            display: flex;
            margin: 40px -11px 0;
        }
        li {
            flex: 1;
            margin: 0 11px;
            background: #ffffff;
            border-radius: 6px;
            border: 1px solid #ebebeb;
            display: flex;
            flex-direction: column;
            figure {
                height: 120px;
                display: flex;
                justify-content: center;
                align-items: center;
                img {
                    width: 80px;
                    height: 80px;
                }
            }

            p {
                flex: 1;
                background: #f6f6f6;
                border-radius: 0px 0px 6px 6px;
                padding: 16px 10px 16px 16px;
                box-sizing: border-box;
                font-size: 14px;
                color: #000000;
                line-height: 22px;
            }
        }
    }

    .branding-nodata-freedom {
        margin-top: 130px;
        text-align: center;
        h2 {
            color: #000000;
            font-size: 24px;
            line-height: 26px;
        }
        h3 {
            margin-top: 8px;
            font-size: 16px;
            font-weight: normal;
            color: #555555;
            line-height: 22px;
        }

        figure {
            margin-top: 16px;
            padding-bottom: 35%;
            position: relative;
            img {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
                border-radius: 8px;
            }
        }

        p {
            font-size: 14px;
            color: #000000;
            line-height: 22px;
            margin-top: 16px;
        }

        button {
            width: 260px;
            height: 40px;
            margin-top: 36px;
            font-size: 14px;
        }
    }

    .branding-nodata-note {
        margin-top: 60px;
        border-top: 1px solid #eee;
        padding-top: 40px;

        h2 {
            font-size: 21px;
            color: #000000;
            line-height: 24px;
            margin-bottom: 15px;
        }

        p {
            font-size: 14px;
            color: #000000;
            line-height: 22px;
        }
    }
}

.branding-list {
    flex: 1;
    position: relative;
    z-index: 0;
    display: flex;
    flex-direction: column;

    & > .loading {
        position: fixed;
        left: 228px;
        top: 0;
        bottom: 0;
        right: 0;
    }

    .branding-list-title {
        display: flex;
        height: 72px;
        strong {
            flex: 1;
            background: #fff;
            border-radius: 8px;
            font-size: 32px;
            color: #000000;
            text-align: center;
            line-height: 72px;
        }
        span {
            margin-left: 20px;
            width: 224px;
            height: 40px;
            padding: 16px;
            background: #fff;
            border-radius: 8px;

            button {
                width: 100%;
            }
        }
    }

    .branding-list-warp {
        flex: 1;
        background: #fff;
        border-radius: 8px;
        margin-top: 20px;
        position: relative;

        table {
            width: 100%;
            border-collapse: collapse;
            thead {
                th {
                    position: relative;
                    text-align: center;
                    border-bottom: 1px solid #dcdcdc;
                    height: 60px;
                    line-height: 36px;
                    font-size: 14px;
                    color: #000000;
                    white-space: nowrap;
                    padding: 0;
                    &::before {
                        content: '';
                        display: block;
                        position: absolute;
                        width: 1px;
                        height: 18px;
                        background: #dcdcdc;
                        right: 0;
                        top: 50%;
                        transform: translateY(-50%);
                    }
                    &:first-child {
                        border-radius: 2px 0 0 2px;
                    }
                    &:last-child {
                        border-radius: 0 2px 2px 0;
                        &::before {
                            display: none;
                        }
                    }

                    &:nth-child(1) {
                        width: 13.36%;
                    }
                    &:nth-child(2) {
                        width: 17.2%;
                    }
                    &:nth-child(3) {
                        width: 11.6%;
                    }
                    &:nth-child(4) {
                        width: 9.8%;
                    }
                    &:nth-child(5) {
                        width: 12.7%;
                    }
                    &:nth-child(6) {
                        width: 18.9%;
                    }
                }
            }
            tbody {
                td {
                    padding: 12px;
                    text-align: center;
                    border-bottom: 1px solid #dcdcdc;
                    font-size: 14px;
                    color: #000000;
                }
                p {
                    line-height: 24px;
                    font-weight: normal;
                    white-space: nowrap;
                    img {
                        height: 24px;
                        margin-right: 4px;
                    }
                }
            }
        }

        .table-input {
            .input-inline {
                margin-top: 8px;
            }
        }

        .table-description {
            text-align: center;
            p > span {
                display: block;
                word-break: break-word;
                white-space: normal;
                font-size: 14px;
                color: #000000;
                line-height: 18px;
                & + span {
                    margin-top: 10px;
                }
            }
        }

        .table-print {
            strong {
                font-weight: normal;
                text-decoration: underline;
                &:hover {
                    color: #ea4c89;
                }
            }

            .popper {
                display: inline-block;
            }
        }

        .table-price {
            .level-discount {
                font-size: 14px;
            }
        }

        .table-sync {
            p {
                width: 102px;
                height: 32px;
                margin: 0 auto;
                cursor: pointer;
                background: #f6f6f6;
                border-radius: 4px;
                line-height: 32px;
                &:hover {
                    background: #e8e8e8;
                }
            }
        }

        .table-store {
            .table-store-nodata,
            .table-store-list {
                display: flex;
                align-items: center;
                width: 184px;
                height: 188px;
                cursor: pointer;
                background: #f6f6f6;
                border-radius: 4px;
                padding: 4px 0;
                padding: 22px 24px;
                box-sizing: border-box;

                &:hover {
                    background: #e8e8e8;
                }
            }

            .table-store-nodata {
                justify-content: center;

                svg {
                    width: 32px;
                    height: 32px;
                    box-sizing: border-box;
                    padding: 8px;
                    fill: #555555;
                    background: #e1e1e1;
                    border-radius: 32px;
                }
                span {
                    font-size: 14px;
                    font-family: Roboto-Regular, Roboto;
                    font-weight: 400;
                    color: #555555;
                    margin-left: 6px;
                }
            }

            .table-store-list {
                flex-direction: column;
                justify-content: center;
                .shop-name {
                    width: 100%;
                    padding: 0;
                    box-sizing: border-box;
                    height: 24px;
                    line-height: 24px;
                    text-align: left;

                    &::v-deep {
                        & > figure {
                            min-width: 24px;
                        }
                        span {
                            flex: 1;
                            overflow: hidden;
                            text-overflow: ellipsis;
                            white-space: nowrap;
                        }
                    }

                    & + .shop-name {
                        margin-top: 16px;
                    }

                    & + :nth-child(n + 5) {
                        display: none;
                    }
                }
            }
        }

        .table-actions {
            button {
                width: 102px;
                height: 32px;
                border-radius: 4px;
                font-size: 14px;
                font-weight: normal;

                & + button {
                    margin-top: 16px;
                }
            }
        }
    }
}

.dialog-remove,
.dialog-leave,
.dialog-edit {
    &::v-deep .dialog-content {
        .dialog-body {
            box-sizing: border-box;
            display: flex;
            flex-direction: column;
            justify-content: space-between;
            align-items: center;
            padding: 40px 20px 26px;
            width: 320px;
            height: 414px;
        }

        figure {
            margin-top: 28px;
            width: 80px;
            height: 80px;

            img {
                width: 100%;
                height: 100%;
            }
        }

        p {
            flex: 1;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 16px;
            color: #000000;
            line-height: 20px;
            text-align: center;
            strong {
                color: #000000;
                font-weight: bold;
                margin-bottom: 8px;
            }
            span {
                line-height: 22px;
            }
        }

        fieldset {
            display: flex;
            flex-direction: column;
            width: 100%;
            button + button {
                margin-top: 8px;
            }
        }
    }
}
</style>
